package com.example.learn

fun main() {
    val array = intArrayOf(-4, 1, 2, 2, 5, 5, 5, 8, 10)
    println("小于等于6的最后一个数的数组下标为：${binarySearch(array, 6)}")
}

private fun binarySearch(array: IntArray, value: Int) : Int {
    var low = 0
    var high = array.size - 1
    while (low <= high) {
        val mid = (low + high) / 2
        if (array[mid] > value) {
            high = mid - 1
        } else if (array[mid] <= value) {
            if (mid == array.size - 1 || array[mid + 1] > value) {
                return mid
            } else {
                low = mid + 1
            }
        }
    }
    return -1
}